package com.urms.service.serviceImpl;

import com.urms.mapper.UserMapper;
import com.urms.pojo.Result;
import com.urms.pojo.Token;
import com.urms.pojo.User;
import com.urms.service.UserService;
import com.urms.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    //角色注册Map
    private final Map<String, UserRole> roleMap;

    public UserServiceImpl() {
        roleMap = new HashMap<>();
        roleMap.put("student", new StudentRole());
        roleMap.put("admin", new AdminRole());
    }

    @Override
    public Result register(User user,String type) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));//密码加密
        UserRole userRole = roleMap.get(type);
        if(userRole == null){
            return Result.error("角色不存在");
        }
        return userRole.register(user);
    }

    @Override
    public Result login(String phone,String password,String type) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));//密码加密
        UserRole userRole = roleMap.get(type);
        if(userRole == null){
            return Result.error("角色不存在");
        }
        User userInfo = (User) userRole.login(user).getData();
        Token tokenInfo = new Token();
        if(userInfo==null){
            return userRole.login(user);
        }else {
            log.info("登录成功，用户信息：{}", userInfo);
            String token = JWTUtils.createToken(userInfo.getId());
            tokenInfo.setToken(token);
            tokenInfo.setId(userInfo.getId());
        }
        return Result.success("登录成功",tokenInfo);
    }

    @Override
    public Result getUserInfo(String token,String type) {
        if(token.equals("")){
            return Result.error("token不能为空");
        }
        Map<String,Object> stringObjectMap = JWTUtils.checkToken(token);
        log.info("token解析结果：{}",stringObjectMap);
        if(stringObjectMap==null|| stringObjectMap.get("id")==null){
            return Result.error("token无效");
        }
        User userInfo;
        if(type.equals("admin")){//判断是否为管理员
            userInfo = userMapper.queryAdminById((Integer) stringObjectMap.get("id"));
        }else{
            userInfo = userMapper.queryStudentById((Integer) stringObjectMap.get("id"));
        }
        if(userInfo==null){
            return Result.error("用户信息不存在");
        }
        return Result.success("获取成功",userInfo);
    }


}
